package filesearch

import javax.swing.JFileChooser
import groovy.io.FileType

/**
 * @author mgg
 *
 */
class FileSearchController {
	
    def model
    def view
	def fileSizeService

 /* Looking for files matching a given pattern */
	def searchFiles = { evt = null ->
	 /* Initializing some variables tied to the ui. Maybe the last two might be 
	  * set up outside the edt */
		execAsync{
			model.searchResultsPanelEnabled = true
			view.dynamicTable.model.clear()
			model.searchEnabled = false
			model.noFiles = 0
			model.noFilesMatch = 0
		}		
		try{
		 /* Enclosing the regex expression because it could also fail*/
			def regex = ~model.fileRegex
		 /* Getting the directory to look for files */
			def directoryStart = new File(model.filePath)
		 /* Searching in the actual directory */
			model.noFiles += directoryStart.list().length
			directoryStart.eachFileMatch(regex,searchByFile)
		 /* Searching in descendants */
			directoryStart.eachDirRecurse{
				model.noFiles += it.list().length
				it.eachFileMatch(regex,searchByFile)
			}
		} finally{
		 /* updating the chart data. This is not updated within the edt because it doesnt
		  * update the ui by itself. */
			view.piedataset.with {
				setValue "No Match", ((model.noFiles - model.noFilesMatch) / model.noFiles) * 100
				setValue "Match", (model.noFilesMatch / model.noFiles) * 100
			}
		 /* Updating the ui */
			execAsync{
				model.searchEnabled = true
				model.searchResultsPanelEnabled = false
			 /* Now the chart is repainted */				
				view.piedataset.fireDatasetChanged()
			}
		}
	}
	
 /* This closure just adds the file to the table model */
	def searchByFile = { f->
		model.noFilesMatch++
	 /* Each time a file is found a new table entry is added */
		execAsync{			
			view.dynamicTable.model.addRow([
				name:f.getName(),
				size: fileSizeService.formatFileSize(f.length()),
				type: f.name.lastIndexOf('.') + 1 != 0 ? f.name.substring(f.name.lastIndexOf('.') + 1) : '',
				lastModified:f.lastModified(),
				path:f.absolutePath
			])
		}
	}
    
 /* Opening the directory where the user wants to look for a given file */
    def browseFiles = { evt = null ->
    	def openResult = view.fileChooserWindow.showOpenDialog(null)
		if (JFileChooser.APPROVE_OPTION == openResult){
			model.filePath = view.fileChooserWindow.selectedFile
			view.whereField.reverseUpdate()
			model.searchEnabled = true
		}
	}
	
 /* Exits the application */
	def exitApplication = {
		app.shutdown()
	}
}
